package com.example.demo.exception;

import com.example.demo.util.RestBean;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestBean<Map<String, String>> handleValidationException(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        fieldError -> Optional.ofNullable(fieldError.getDefaultMessage())
                                .orElse("参数错误")
                ));
        return RestBean.failure(400, errors);
    }

    @ExceptionHandler(BusinessException.class)
    public RestBean<String> handleBusinessException(BusinessException ex) {
        return RestBean.failure(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public RestBean<String> handleAllException(Exception ex) {
        return RestBean.failure(500, "系统繁忙，请稍后重试");
    }
}